package com.atguigu.InternetCoding.chats;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author zeng
 * @data 2021/06/30 9:47
 */
public class ReceiveTalk implements Runnable{
    //设置成员变量
    private DatagramSocket socket = null;
    private DatagramPacket packet = null;
    private int fromport;
    private int port;

    public ReceiveTalk(int port, int fromport) {
        //this.name = name;
        this.fromport = fromport;
        this.port = port;
    }

    @Override
    public void run() {
        //建立UDP接口
        try {
            this.socket = new DatagramSocket(this.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (true) {
            byte[] by = new byte[1024];
            //建立接收信息包
            packet = new DatagramPacket(by,0,by.length);
            //接收信息
            try {
                this.socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //打印信息
            System.out.println(new String(packet.getData()));
            if("bye".equals(new String(packet.getData()))){
                break;
            }
        }
        //关闭信息
        socket.close();
    }
}
